package org.vehicle.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vehicle.common.MyConstant;
import org.vehicle.entity.ManagerInfo;
import org.vehicle.entity.OrganizationInfo;
import org.vehicle.entity.security.MyUserDetail;
import org.vehicle.service.ManagerInfoService;
import org.vehicle.service.OrganizationInfoService;
import org.vehicle.util.ExcelUtil;
import org.vehicle.util.MD5Util;


@Controller
public class ManagerInfoController {
	private static Logger logger = LogManager.getLogger(ManagerInfoController.class.getName());

    @Autowired
    private ManagerInfoService managerInfoService;
    @Autowired
    private OrganizationInfoService organizationInfoService;

    @RequestMapping("managerInfo")
    public String mapInfo(HttpServletRequest req, Model model) {
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		model.addAttribute("manager", ud);
        return "managerInfo";
    }

    @RequestMapping("resetPasswordInit")
    public String resetPasswordInit(HttpServletRequest req, Model model) {
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		model.addAttribute("manager", ud);
        return "resetPassword";
    }

    /**
     * 获取管理员分页
     *
     * @param request
     * @return
     */
    @RequestMapping("/getManagerInfoPage")
    @ResponseBody
    public Map<String, Object> getManagerInfoPage(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String currentPage = request.getParameter("curr");
        String pageSize = request.getParameter("pageSize");
        String managerName = request.getParameter("managerName");
        String certificateCode = request.getParameter("certificateCode");
        try {
        	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("managerName", managerName);
            paramMap.put("certificateCode", certificateCode);
            if(ud.getManagerType()==MyConstant.MANAGER_TYPE_ROOT){
            	paramMap.put("managerType",MyConstant.MANAGER_TYPE_ADMIN);
            }else{
            	paramMap.put("managerType",MyConstant.MANAGER_TYPE_USER);
            	paramMap.put("organizationInfoId",ud.getOrganizationInfoId());
            }
            map = managerInfoService.getManagerInfoPage(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * @param request
     * @return
     * @describe: 添加/修改
     * @Author: ruifight2018
     * @Date: 2018年6月11日 下午6:45:15
     */
    @RequestMapping("/saveManagerInfo")
    @ResponseBody
    public Map<String, Object> saveManagerInfo(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
        	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String id = request.getParameter("managerinfoid");
            String managername = request.getParameter("managername");
            String jobnumber = request.getParameter("jobnumber");
            String certificatecode = request.getParameter("certificatecode");
            String mobilephone = request.getParameter("mobilephone");
            String loginname = request.getParameter("loginname");
            Long organizationInfoId = Long.parseLong(request.getParameter("organizationInfoId"));

            ManagerInfo managerInfo = new ManagerInfo();
            managerInfo.setManagerName(managername);
            managerInfo.setJobNumber(jobnumber);
            managerInfo.setCertificateCode(certificatecode);
            managerInfo.setMobilePhone(mobilephone);
            managerInfo.setOrganizationInfoId(organizationInfoId);
            managerInfo.setCreateDate(new Date());
            managerInfo.setManagerState(1);
            if(ud.getManagerType()==MyConstant.MANAGER_TYPE_ROOT){
            	managerInfo.setManagerType(MyConstant.MANAGER_TYPE_ADMIN);
            }else{
            	managerInfo.setManagerType(MyConstant.MANAGER_TYPE_USER);
            }
            Map<String, Object> paramMap=new HashMap<String, Object>();
            paramMap.put("managerInfoId", id);
            paramMap.put("loginName", loginname);
			paramMap.put("certificateCode", certificatecode);
			ManagerInfo tempManagerInfo=managerInfoService.getManagerInfoByLoginName(paramMap);
			if(tempManagerInfo!=null){
				result.put("state", 0);
                result.put("msg", "登录名已存在");
                return result;
			}
			ManagerInfo tempManagerInfo2=managerInfoService.getManagerInfoByCertificateCode(paramMap);
			if(tempManagerInfo2!=null){
				result.put("state", 0);
                result.put("msg", "身份证号已存在");
                return result;
			}
            if (null != id && !id.equals("")) {
                Long managerinfoid = Long.valueOf(id);
                managerInfo.setManagerInfoId(managerinfoid);
                managerInfoService.updateByPrimaryKeySelective(managerInfo);
                result.put("msg", "修改成功");
                result.put("state", 1);
            } else {
                managerInfo.setPassword(MD5Util.MD5(MyConstant.DEFAULT_PASSWORD));
                managerInfo.setLoginName(loginname);
                managerInfoService.insert(managerInfo);
                result.put("state", 1);
                result.put("msg", "添加成功,默认密码为："+MyConstant.DEFAULT_PASSWORD);

            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("state", 0);
            result.put("msg", "操作失败");
        }
        return result;
    }


    /**
     * @param key
     * @return
     * @describe: 删除管理员
     * @Author: ruifight2018
     * @Date: 2018年6月11日 下午6:41:27
     */
    @RequestMapping("/delManagerInfo")
    @ResponseBody
    public Map<String, Object> delManagerInfo(Long key) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {

            managerInfoService.deleteByPrimaryKey(key);
            result.put("num", 1);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("num", 0);
        }
        return result;
    }

    /**
     * @param key
     * @return
     * @describe: 回显
     * @Author: ruifight2018
     * @Date: 2018年6月11日 下午6:42:00
     */
    @RequestMapping("/viewManagerInfoDetail")
    @ResponseBody
    public ManagerInfo viewManagerInfoDetail(Long key) {
        ManagerInfo kcManagerinfo = managerInfoService.selectByPrimaryKey(key);
        return kcManagerinfo;
    }

    /**
	 * 导入黑名单
	 * @param req
	 * @return
	 */
	@RequestMapping("importManager")
	@ResponseBody
	public Map<String, Object> importManager(HttpServletRequest req){
        MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String, Object> map=new HashMap<String, Object>();
		List<Map<String, String>> dataList=new ArrayList<Map<String, String>>();;
		Map<String, Object> dataMap=ExcelUtil.getExcelData(req);
		String errorMsg=(String) dataMap.get("errorMsg");
		map.put("errorMsg", errorMsg);
		if(!StringUtils.isEmpty(errorMsg)){
			 map.put("errorMsg", errorMsg);
			 return map;
		}
		dataList=(List<Map<String, String>>) dataMap.get("dataList");
		for(Map<String, String> cellMap:dataList){
			ManagerInfo managerInfo=new ManagerInfo();
			if(StringUtils.isEmpty(cellMap.get("col0"))&&StringUtils.isEmpty(cellMap.get("col1"))&&StringUtils.isEmpty(cellMap.get("col2"))
					&&StringUtils.isEmpty(cellMap.get("col3"))&&StringUtils.isEmpty(cellMap.get("col4"))&&StringUtils.isEmpty(cellMap.get("col5"))){
				continue;
			}else{
				String managerName=null;
				String organizationInfoName=null;
				String jobNumber=null;
				String certificateCode=null;
				String mobilePhone=null;
				String loginName=null;
				try{
					OrganizationInfo organizationInfo=null;
					if(ud.getManagerType()==MyConstant.MANAGER_TYPE_ROOT){
						managerName=cellMap.get("col0");
						organizationInfoName=cellMap.get("col1");
						jobNumber=cellMap.get("col2");
						certificateCode=cellMap.get("col3");
						mobilePhone=cellMap.get("col4");
						loginName=cellMap.get("col5");
						Map<String, Object> paramMap=new HashMap<String, Object>();
						paramMap.put("organizationName", organizationInfoName);
						organizationInfo=organizationInfoService.getOrganizationInfoByName(paramMap);
						managerInfo.setManagerType(MyConstant.MANAGER_TYPE_ADMIN);
					}else{
						managerName=cellMap.get("col0");
						jobNumber=cellMap.get("col1");
						certificateCode=cellMap.get("col2");
						mobilePhone=cellMap.get("col3");
						loginName=cellMap.get("col4");
						organizationInfo=new OrganizationInfo();
						organizationInfo.setOrganizationInfoId(ud.getOrganizationInfoId());
						managerInfo.setManagerType(MyConstant.MANAGER_TYPE_USER);
					}
					
					if(organizationInfo==null){
		        		cellMap.put("msg", "管理站名称不存在");
		        		continue;
		        	}
					if(StringUtils.isEmpty(managerName)){
		        		cellMap.put("msg", "管理姓名不能为空");
		        		continue;
		        	}
					if(StringUtils.isEmpty(certificateCode)){
		        		cellMap.put("msg", "身份证号不能为空");
		        		continue;
		        	}
					if(StringUtils.isEmpty(loginName)){
		        		cellMap.put("msg", "登录名不能为空");
		        		continue;
		        	}
					Map<String, Object> paramMap=new HashMap<String, Object>();
					paramMap.put("loginName", loginName);
					paramMap.put("certificateCode", certificateCode);
					ManagerInfo tempManagerInfo=managerInfoService.getManagerInfoByLoginName(paramMap);
					if(tempManagerInfo!=null){
						cellMap.put("msg", "登录名已经存在");
		        		continue;
					}
					ManagerInfo tempManagerInfo2=managerInfoService.getManagerInfoByCertificateCode(paramMap);
					if(tempManagerInfo2!=null){
						cellMap.put("msg", "身份证号已经存在");
		        		continue;
					}
		        	managerInfo.setManagerName(managerName);
					managerInfo.setJobNumber(jobNumber);
					managerInfo.setCertificateCode(certificateCode);
					managerInfo.setOrganizationInfoId(organizationInfo.getOrganizationInfoId());
					managerInfo.setMobilePhone(mobilePhone);
					managerInfo.setLoginName(loginName);
					managerInfo.setCreateDate(new Date());
					managerInfo.setManagerState(1);
					managerInfoService.insertSelective(managerInfo);
					cellMap.put("msg", "添加成功");
				}catch(Exception e){
					logger.error("导入管理站异常", e);
					cellMap.put("msg", "添加失败");
				}
			}
		}
		map.put("dataList", dataList);
		return map;
	}
	
	
	/**
	 * 重置密码
	 * @param req
	 * @return
	 */
	@RequestMapping("resetPassword")
	@ResponseBody
	public Map<String, Object> resetPassword(HttpServletRequest req){
		Map<String, Object> result=new HashMap<String, Object>();
		try{
			String id=req.getParameter("key");
			ManagerInfo managerInfo=new ManagerInfo();
			managerInfo.setManagerInfoId(Long.parseLong(id));
			managerInfo.setPassword(MD5Util.MD5(MyConstant.DEFAULT_PASSWORD));
			managerInfoService.updateByPrimaryKeySelective(managerInfo);
			result.put("num", 1);
		}catch(Exception e){
			logger.error(e);
			result.put("num", 0);
		}
		return result;
	}
	
	
	/**
	 * 修改密码
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateManagerPassword")
	@ResponseBody
	public Map<String, Object> updateManagerInfo(HttpServletRequest request) {
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String, Object> result=new HashMap<String, Object>();
		try {
			Long managerInfoId = ud.getManagerInfoId();
			String md5 = MD5Util.MD5(request.getParameter("newPassword1"));
			ManagerInfo tempManagerInfo=managerInfoService.selectByPrimaryKey(managerInfoId);
			if(md5.equals(tempManagerInfo.getPassword())){
				result.put("isSuccess", 0);
				result.put("msg", "修改失败，与原密码相同");
				return result;
			}
			ManagerInfo managerInfo=new ManagerInfo();
			managerInfo.setManagerInfoId(managerInfoId);
			managerInfo.setPassword(md5);
			managerInfoService.updateByPrimaryKeySelective(managerInfo);
			result.put("isSuccess", 1);
		}catch (Exception e) {
			logger.error(e);
			result.put("isSuccess", 0);
			result.put("msg", "修改失败");
		}
		return result;
	}
}
